#!/usr/bin/ruby

require 'cgi'

$cgi =  CGI.new("html3")

def calcForm(left, op, right, value)
   addselected = (op=="add")?"selected":""
   mulselected = (op=="mul")?"selected":""
   return <<-END
   <center><h1>Welcome to the calculator!</h1></center><br>
   <form target="calc.cgi">
      <center> 
         <input type="text" name="left" value="#{left}">
         <select name="op">
            <option value="add" #{addselected}>+</option>
            <option value="mul" #{mulselected}>*</option>
         </select>
         <input type="text" name="right" value="#{right}">
         =
         #{value}
         <br
         <input type="submit" name="action" value="calculate">
      </center>
   </form>
END
end

if $cgi.has_key?('left') &&  $cgi.has_key?('right') then
   left  = $cgi['left'].to_i()
   right = $cgi['right'].to_i()
   op    = $cgi['op']
   if op == "add" then
     value = (left + right).to_s
   else
     value = (left * right).to_s
   end
else
   left  = ""
   right = ""
   op    = "add"
   value = ""
end

$cgi.out { 
  $cgi.html { 
    $cgi.body {
         calcForm(left,op,right,value)
    }
  }
}
